package com.computer.fundamentals.algorithm;

import com.computer.fundamentals.algorithm.sort.InsertSort;
import com.computer.util.Constant;
import com.computer.util.UniversalMethod;

public class BinarySearch {

    /**
     * 二分查找
     */
    public static int binarySearch(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[mid] > target) {
                right = mid - 1;
            }else {
                left = mid + 1;
            }
        }
        return -1;
    }

    /**
     * 测试
     */
    public static void main(String[] args) {

        System.out.println("------------数组------------");
        int[] array = UniversalMethod.createArray(Constant.DEFAULT_ARRAY_LENGTH);
        InsertSort.insertSort(array);
        UniversalMethod.printArray(array);
        System.out.println("\n");

        System.out.println("------------输出目标位置------------");
        System.out.println(binarySearch(array, 29));
    }
}
